import {baseUrl} from "@/apis/api"

/**
 * 发送请求
 */
export const processRequest = ({api, method, data}) => {
    uni.showLoading({
        title: "请求数据中，请稍等"
    })
    return new Promise((resolve, reject) => {
        uni.getStorage({
            key: "token",
            complete: (res) => {
                const token = res.data ? "Bearer " + res.data : ''
                uni.request({
                    url: baseUrl + api,
                    method: method,
                    data: data,
                    header: {
                        'authorization': token
                    },
                    success: (res) => {
                        console.log(res)
                        uni.hideLoading()
                        if (res.statusCode === 401) {
                            uni.removeStorage({
                                key: "token",
                                success: () => {
                                    uni.showToast({
                                        title: "您的登录凭据已过期，请重新登录",
                                        icon: "none",
                                        musk: true,
                                        duration: 2000
                                    })
                                    setTimeout(() => {
                                        uni.reLaunch({
                                            url: '/frame/pages/login/index'
                                        })
                                    }, 1500)
                                }
                            })
                        } else {
                            const resultData = res.data
                            if (resultData.status === 200) {
                                resolve(resultData.data)
                            } else if (resultData.status === 500) {
                                uni.showToast({
                                    title: "服务器出现错误，请联系管理员处理！",
                                    icon: "none"
                                })
                                reject()
                            } else {
                                uni.showToast({
                                    title: resultData.message,
                                    icon: "none"
                                })
                                reject()
                            }
                        }
                    },
                    fail: (res) => {
                        uni.hideLoading()
                        uni.showToast({
                            title: "服务器出现错误，请联系管理员处理！",
                            icon: "none"
                        })
                        reject()
                    }
                })
            }
        })
    })
}